﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using System.Data;

namespace DBUtil.Provider.SqlServer;

public partial class SqlServerAccess : DBAccess
{
    public override async Task BulkCopyAsync(DataTable dt, string tableName = null, int timeoutSeconds = 60 * 30, int notifyAfter = 0, Func<long, Task<bool>> callBack = null, CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrWhiteSpace(tableName)) tableName = dt.TableName;
        if (string.IsNullOrWhiteSpace(tableName)) throw new Exception("必须指定要目的表名!");
        SqlBulkCopy sbc = null;
        if (IsTransaction) sbc = new SqlBulkCopy((SqlConnection)CurrentConnection, SqlBulkCopyOptions.Default, (SqlTransaction)CurrentTransaction);
        else if (IsSession) sbc = new SqlBulkCopy((SqlConnection)CurrentConnection);
        else sbc = new SqlBulkCopy((SqlConnection)GetNewConnection());

        sbc.BulkCopyTimeout = timeoutSeconds;
        sbc.DestinationTableName = tableName;
        sbc.NotifyAfter = notifyAfter;
        if (callBack != null) sbc.SqlRowsCopied += async (object sender, SqlRowsCopiedEventArgs e) =>
        {
            e.Abort = await callBack(e.RowsCopied);
        };

        for (int i = 0; i < dt.Columns.Count; i++)
        {
            sbc.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
        }
        await sbc.WriteToServerAsync(dt);
    }
}
